//
//  UserAccountViewController.m
//  CheekiOS
//
//  Created by mac on 2017/6/21.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UserAccountViewController.h"
#import "UserAccountCell.h"
#import "YD_purchaseCharms.h"//第三方
#import "YD_purchaseView.h"//第三方
#import "UserAccountTradingController.h"
//内购
#import <StoreKit/StoreKit.h>
//充值协议
#import "UserAgreementWebController.h"




//BeeCloudDelegate第三方支付
@interface UserAccountViewController ()<UITableViewDelegate, UITableViewDataSource, UserAccountCellDelegate,SKProductsRequestDelegate, SKPaymentTransactionObserver>{
    
    int recordPayType_;
    
//    PayChannel _currentChannel;
    
    NSString * _billTitle;
    
    NSString *_billno;
    

}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UserpersionlInfoModel *infomodel;
@property (nonatomic, strong) NSArray *NumberArray;
@property (nonatomic, strong) NSArray *MoneyArray;

@property (nonatomic, strong) NSString *moneyStr;//支出钱
@property (nonatomic, strong) NSString *payMoneyStr;//获得钻石

@property (nonatomic, strong) SKProductsRequest *requestSk;
@property (nonatomic, strong) NSString *productID;

@end

@implementation UserAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

    
    
    recordPayType_ = 1;
    _productID = @"";
    _moneyStr = @"";
    _payMoneyStr = @"";
    
    
    [self setNavgationBarHidden];
    
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 64)];
    bgView.backgroundColor = Colorbackground;
    [self.view addSubview:bgView];

    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(22, 19.5, 44, 44)];
    btn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft ;//设置文字位置，现设为居左，默认的是居中
    
    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 5.5, 0, 0);
    [btn addTarget:self action:@selector(backActionbtn) forControlEvents:UIControlEventTouchUpInside];
    
    
    CGFloat TopsegmentFloat ;
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
        NSLog(@"ipad");
        TopsegmentFloat =0;
        
    }else{
        TopsegmentFloat = 16;
        
        NSLog(@"iphone or ipod");
    }
    
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, TopsegmentFloat, KScreenWidth, 44*SCREEN_WIDTH_RATIO47)];
    titleLab.text = @"账户";
    titleLab.font = [UIFont systemFontOfSize:18];
    titleLab.textColor = ColorI(0x2e353f);
    titleLab.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:titleLab];
    [bgView addSubview:btn];


    
    self.title = @"账户";
    _NumberArray = @[@"42",@"210",@"686",@"2086"];
    _MoneyArray = @[@"6",@"30",@"98",@"298"];
    UIImageView *headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 205*SCREEN_WIDTH_RATIO47)];
    headerView.image = [UIImage imageNamed:@"grzx_account_illustration"];
    headerView.contentMode = UIViewContentModeScaleAspectFill;
    headerView.userInteractionEnabled = YES;

    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn addTarget:self action:@selector(leftTopHelp) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setTitle:@"充值帮助" forState:UIControlStateNormal];
    leftBtn.frame = CGRectMake(15, headerView.bottom-55*SCREEN_WIDTH_RATIO47, 70, 25);
    leftBtn.titleLabel.font = FontP(15);
    [leftBtn setTitleColor:ColorI(0x2d353f) forState:UIControlStateNormal];
    
    [headerView addSubview:leftBtn];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn addTarget:self action:@selector(rightBtndetails) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"账户明细" forState:UIControlStateNormal];
    rightBtn.frame = CGRectMake(headerView.width-70-15, headerView.bottom-55*SCREEN_WIDTH_RATIO47, 70, 25);
    rightBtn.titleLabel.font = FontP(15);
    [rightBtn setTitleColor:ColorI(0x2d353f) forState:UIControlStateNormal];
    
    [headerView addSubview:rightBtn];
    [self requestDate];

    
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, bgView.bottom, KScreenWidth, KScreenHeight-64) style:UITableViewStylePlain];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    self.tableView.tableHeaderView = headerView;
    
    
 
    
}
- (void)backActionbtn{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)agreementButton{
    NSLog(@"充值协议");
    UserAgreementWebController *vc = [[UserAgreementWebController alloc]init];
    vc.UrlStr = HttpUrlStringS(@"userchongzhi.html");
    vc.setTitle = @"充值协议";
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

- (void)leftTopHelp{
        NSLog(@"充值帮助");
    
    UserAgreementWebController *vc = [[UserAgreementWebController alloc]init];
    vc.setTitle = @"充值帮助";
    vc.UrlStr = HttpUrlStringS(@"chongzhibangzhu.html");
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)rightBtndetails{
    UserAccountTradingController *vc = [[UserAccountTradingController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)requestDate{
    
    
    
    [HcardHttpmanager getPersionalInfosuccess:^(id sucess) {
        
        self.infomodel = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];

        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    [SVProgressHUD dismiss];


}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 4;
    }else{
        return 1;
    }
    
 }

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        static NSString *userAccountCellIdentOne = @"userAccountCellIdentOne";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:userAccountCellIdentOne];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:userAccountCellIdentOne];
            
        }
        for (UIView * subView in cell.contentView.subviews){
            if ([subView isKindOfClass:[UILabel class]]) {
                [subView removeFromSuperview];
            }
        }
        UILabel *numberLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, KScreenWidth, 40)];
        numberLab.text = [NSString stringWithFormat:@"%ld钻石",(long)_infomodel.charm];
        numberLab.textColor = ColorI(0x5978b6);
        numberLab.textAlignment = NSTextAlignmentCenter;
        numberLab.font = FontP(18);
        [cell.contentView addSubview:numberLab];
        
        UILabel *textLab = [[UILabel alloc]initWithFrame:CGRectMake(0, numberLab.bottom+5, KScreenWidth, 30)];
        textLab.text = @"账户余额";
        textLab.textColor = [UIColor blackColor];
        textLab.textAlignment = NSTextAlignmentCenter;
        textLab.font = FontP(16);
        [cell.contentView addSubview:textLab];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1){
    
        UserAccountCell *cell = [UserAccountCell cellWithTableView:tableView indexPath:indexPath];
        cell.delegate = self;
        cell.firstCharge = _infomodel.firstCharge;
        cell.numberArray = _NumberArray;
        cell.numberMoneyArray = _MoneyArray;
        
        
        return cell;
    
    }else{
        static NSString *userAccountCellIdentOneButton = @"userAccountCellIdentOneButton";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:userAccountCellIdentOneButton];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:userAccountCellIdentOneButton];
            
        }
        for (UIView * subView in cell.contentView.subviews){
            if ([subView isKindOfClass:[UIButton class]]) {
                [subView removeFromSuperview];
            }
        }
        UIButton *agreementButton = [UIButton buttonWithType:UIButtonTypeCustom];
        agreementButton.titleLabel.font = FontP(12);
        [agreementButton setTitleColor:ColorI(0x2e353f) forState:UIControlStateNormal];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"已阅读并同意《用户充值协议》"];
        NSRange strRange = {7,6};
        [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
        [agreementButton setAttributedTitle:str forState:UIControlStateNormal];
        agreementButton.frame = CGRectMake(0, 5, KScreenWidth, 20);
        [agreementButton addTarget:self action:@selector(agreementButton) forControlEvents:UIControlEventTouchUpInside];
        agreementButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [cell addSubview:agreementButton];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 100;
    }else if (indexPath.section == 1){
        return 60;
    }else{
        
        return 30;
    }
}
//充值
- (void)numBtnClickAction:(UIButton *)sender{
    
    

    if (sender.tag == 0) {
        _productID = ProductID_IAP0p6;
        _moneyStr = @"6.00";
        _payMoneyStr = @"42";
        
        
        
    }else if (sender.tag == 1){
        _productID = ProductID_IAP1p30;
        _moneyStr = @"30.00";
        _payMoneyStr = @"210";

    }else if (sender.tag == 2){
        _productID = ProductID_IAP2p98;
        _moneyStr = @"98.00";
        _payMoneyStr = @"686" ;

    }else{
        _productID = ProductID_IAP3p298;
        _moneyStr = @"298.00";
        _payMoneyStr = @"2086" ;

    }
    
    WEAKSELF
    if ([SKPaymentQueue canMakePayments]) {
        NSLog(@"允许");
        [weakSelf requestProductData:_productID];
    }else{
        NSLog(@"不允许");
    }
    [SVProgressHUD show];
}

-(void)requestProductData:(NSString *)ProductId{
    NSLog(@"请求对应的产品信息");
    NSSet *nsset = [NSSet setWithObjects:ProductId, nil];
    _requestSk = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    _requestSk.delegate = self;
    [_requestSk start];
}

//收到产品信息

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    NSLog(@"收到产品返回信息");
    
    NSArray *productArr = response.products;
    if (productArr.count == 0) {
        NSLog(@"没有数据");
        return;
    }
    
    NSLog(@"productID：%@",response.invalidProductIdentifiers);
    NSLog(@"产品付费数量:%lu",(unsigned long)[productArr count]);
    
    SKProduct *prod = nil;
    
    for (SKProduct *pro in productArr) {
        NSLog(@"%@",pro.description);
        NSLog(@"%@",pro.localizedDescription);
        NSLog(@"%@",pro.localizedTitle);
        NSLog(@"%@",pro.price);
        NSLog(@"%@",pro.productIdentifier);
        
        if ([pro.productIdentifier isEqualToString:_productID]) {
            prod = pro;
        }
    }
    
    if (prod != nil) {
        SKPayment  *payment = [SKPayment paymentWithProduct:prod];
        
        NSLog(@"发送购买请求");
        [[SKPaymentQueue defaultQueue] addPayment:payment];
        
    }
    

}

//失败请求

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    [SVProgressHUD dismiss];
    NSLog(@"-----------错误-------------");
    [SVProgressHUD showWithStatus:@"购买失败"];
}

-(void)requestDidFinish:(SKRequest *)request{
    NSLog(@"请求信息结束");
}



-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction *tran in transactions) {
        NSLog(@"打印错误日志----%@",tran.error.description);
        
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{
                NSLog(@"交易完成");
                [self completeTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateFailed:{//交易失败
                [self failedTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateRestored:{//已经购买过该商品
                [self restoreTransaction:tran];
            }
                break;
            case SKPaymentTransactionStatePurchasing:      //商品添加进列表
                NSLog(@"商品添加进列表");
                break;
            default:
                break;
        }
        
        
    }
    [SVProgressHUD dismiss];
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    if(transaction.error.code != SKErrorPaymentCancelled) {
        NSLog(@"购买失败");
    } else {
        NSLog(@"用户取消交易");
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    WEAKSELF
    
   
    if (transaction.transactionState == SKPaymentTransactionStatePurchased) {
        NSString *note = @"苹果内购";
        
        [HcardHttpmanager inOutCharmWithCharm:_payMoneyStr withCost:_moneyStr withNote:note withType:KInCharmType withTransNo:nil withCharm1:nil withfirstCharge:_infomodel.firstCharge  success:^(id result) {
            if(result){
                
                [weakSelf requestDate];
                
            }
        } failure:^(NSError *error) {
            
        }];
        NSLog(@"交易结束");
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

}


- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    // 对于已购商品，处理恢复购买的逻辑
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
#pragma mark ==============第三方支付代理=============
//- (void)numBtnClickAction:(UIButton *)sender{
//    
//    self.moneyStr = @"";
//    self.moneyStr = [NSString stringWithFormat:@"%@",_NumberArray[sender.tag]];
//    self.payMoneyStr = @"";
//    self.payMoneyStr = [NSString stringWithFormat:@"%@",_MoneyArray[sender.tag]];
//    
//    [YD_purchaseView showWithDelegate:self witnMoney:self.moneyStr PayMoney:self.payMoneyStr];
//
//}
//#pragma mark--btnClickDelegate
//-(void)didClickBtn:(UIButton *)sender{
//    switch (sender.tag) {
//        case 0:
//            
//            recordPayType_ = 0;
//            break;
//        case 1:
//            
//            recordPayType_ = 1;
//            break;
//        case 2:
//            
//            [YD_purchaseView Hide];
//            break;
//        default:
//            break;
//    }
//    if(sender.tag!=2){
//        return;
//    }
//    if(recordPayType_==1){//支付宝
//        [self doPay:PayChannelAliApp];
//    }else{
//        [self doPay:PayChannelWxApp];
//    }
//    
//}
//
//#pragma mark - 微信、支付宝
//- (void)doPay:(PayChannel)channel {
//    _billno = [self genBillNo];
//    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value",@"key", nil];
//    BCPayReq *payReq = [[BCPayReq alloc] init];
//    /**
//     *  支付渠道，PayChannelWxApp,PayChannelAliApp,/(PayChannelUnApp,PayChannelBaiduApp)(略)
//     */
//    //测试：
//    _billTitle = @"贴脸儿钻石充值";
//    payReq.channel = channel; //支付渠道
//    payReq.title = _billTitle;//订单标题
//    //payReq.totalFee =[NSString stringWithFormat:@"%lf",[self.moneyStr doubleValue]*0.01] ;
//    payReq.totalFee = [NSString stringWithFormat:@"%.2ld",[_payMoneyStr integerValue]*100];//订单价格;
//    payReq.billNo = _billno;//商户自定义订单号
//    payReq.scheme = @"AlipayShanyue";//URL Scheme,在Info.plist中配置; 支付宝,银联必有参数
//    payReq.billTimeOut = 300;//订单超时时间
//    payReq.viewController = self; //银联支付和Sandbox环境必填
//    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
//    [BeeCloud sendBCReq:payReq];
//}
//
//#pragma mark - 生成订单号
//- (NSString *)genBillNo {
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];
//    return [formatter stringFromDate:[NSDate date]];
//}
//
//#pragma mark - BCPay回调
//- (void)onBeeCloudResp:(BCBaseResp *)resp {
//    switch (resp.type) {
//        case BCObjsTypePayResp:
//        {
//            // 支付请求响应
//            BCPayResp *tempResp = (BCPayResp *)resp;
//            if (tempResp.resultCode == 0) {
//                BCPayReq *payReq = (BCPayReq *)resp.request;
//                //百度钱包比较特殊需要用户用获取到的orderInfo，调用百度钱包SDK发起支付
//                if (payReq.channel == PayChannelBaiduApp && ![BeeCloud getCurrentMode]) {
//                    
//                } else {
//                    //test：模拟支付（ownService）
//                    NSString *note = @"苹果内购";
//                    NSString *transNo =_billno;
//                    [HcardHttpmanager inOutCharmWithCharm:self.moneyStr withCost:_payMoneyStr withNote:note withType:KInCharmType withTransNo:transNo withCharm1:@"" success:^(id result) {
//                        if(result){
//                            //微信、支付宝、银联支付成功
//                            // [self showAlertView:resp.resultMsg];
//                            [self.navigationController popViewControllerAnimated:YES];
//                        }
//                    } failure:^(NSError *error) {
//                        
//                    }];
//                    
//                }
//            } else {
//                //支付取消或者支付失败
//                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
//            }
//        }
//            break;
//        default:
//            break;
//    }
//}
//- (void)showAlertView:(NSString *)msg {
//    
//    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    [alert show];
//}
//-(void)viewWillDisappear:(BOOL)animated{
//    [YD_purchaseView Hide];
//}

@end
